﻿/*****************************************************公共方法*************************************************************/
//名称：公共方法JS
//功能：共同方法
//创建人：王群
//开发人员：王群
//创建日期：2013-09-26
/*****************************************************公共方法*************************************************************/

//验证普通单行文本
var commonRegex2 = /^[a-zA-Z0-9,   ，\r\n《.。》？?;:：“”；{}【】『』|、\-~!@#$^&*()_+～！@#￥……&×（）——=\u4e00-\u9fa5]+$/i;
var commonRegex = /^[a-zA-Z0-9,   ，\r\n 《.。》？?;:：“”；{}【】『』\/|、\-~!@#$^&*()_+～！@#￥……&×（）——=\u4e00-\u9fa5]+$/i;
var commonSearchRegex = /^[a-zA-Z0-9,   ，\r\n 《.。》？?;:：“”；{}【】『』\/|、\-\\-~!@#$^&*()_+～！@#￥……&×（）——=\u4e00-\u9fa5]+$/i;
//var commonRegexText = "只能输入半角字符和符号，全角字符和符号或特殊字符（'\\/\"%><[]）不允许输入！";
var commonRegexText = "输入格式不正确！";

//验证编码
var commonRegex_Identification = /^[A-Za-z0-9-.-_]+$/;
var commonRegexText_Identification = '编码输入值为非法字符！';

////验证名称
var commonRegex_Name = /^[a-zA-Z0-9,   ，\r\n 《.。》？?;:：“”；{}【】『』|、\-~!@#$^&*()_+～！@#￥……&×（）——=\u4e00-\u9fa5]+$/i;
var commonRegexText_Name = '名称输入值为非法字符！';

////验证英文名称
//var commonRegex_EnglishName = /^[A-Za-z-_ ]+$/;
//var commonRegexText_EnglishName = '英文名称只能允许输入A-Za-z-_这些字符！';


//验证图标文件全名(【图标管理】使用，文件全名也可以输入路径 /.)
var commonRegex_IconFullName = /^[a-zA-Z0-9,   ，\/《.。》？?;:{}【】『』|、\-~!@#$^&*()_+～！@#￥……&×（）——=\u4e00-\u9fa5]+$/i;
//var commonRegexText_IconFullName = "只能输入半角字符和符号，全角字符和符号或特殊字符（'\\\"%><[]）不允许输入！";
var commonRegexText_IconFullName = "输入格式不正确！";

var ajaxRequestFail = "ajax请求失败";
////是否使用其他功能
var isUseOtherFunction = true;
////是否检查密码复杂性
var isCheckPassword = false;
////检查用户是否为首次登录
var isCheckFirstLogin = false;
//保存信息到cookie里面
//name:cookie的名称；value：名称对应的值； expireHours:cookie保存信息的失效时间 单位：小时
function addcookie(name, value, expireHours) {
    var cookieString = name + "=" + escape(value);
    //判断是否设置过期时间
    if (expireHours > 0) {
        var date = new Date();
        date.setTime(date.getTime + expireHours * 3600 * 1000);
        cookieString = cookieString + "; expire=" + date.toGMTString();
    }
    document.cookie = cookieString;
}

//根据cookie名称获取对应的数值
function getcookie(name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) return unescape(arr[1]);
    }
    return "";
}

Ext.override(Ext.grid.column.RowNumberer, {
    renderer: function (value, metaData, record, rowIdx, colIdx, store) {
        var rowspan = this.rowspan, size = store.pageSize,
            page = store.currentPage,
            result = record.index;
        if (page > 1) {
            result = null;
        }
        if (rowspan) {
            metaData.tdAttr = 'rowspan="' + rowspan + '"';
        }

        if (result == null) {
            result = rowIdx;
            if (page > 1) {
                result += (page - 1) * store.pageSize;
            }
        }
        return result + 1;
    }
});
////重写CheckColumn的方法processEvent使stopSelection配置项有效（禁用编辑）
Ext.override(Ext.grid.column.CheckColumn, {
    processEvent: function (type, view, cell, recordIndex, cellIndex, e, record, row) {
        var me = this,
            key = type == 'keydown' && e.getKey(),
            mousedown = type == 'mousedown';

        if (!me.disabled && (mousedown || (key == e.ENTER || key == e.SPACE))) {
            var dataIndex = me.dataIndex,
                checked = !record.get(dataIndex);

            // Allow apps to hook beforecheckchange
            if (me.fireEvent('beforecheckchange', me, recordIndex, checked) !== false) {
                if (!me.stopSelection) return false;
                record.set(dataIndex, checked);
                me.fireEvent('checkchange', me, recordIndex, checked);

                // Mousedown on the now nonexistent cell causes the view to blur, so stop it continuing.
                if (mousedown) {
                    e.stopEvent();
                }
                // Prevent the view from propagating the event to the selection model - we have done that job.
                return false;
            } else {
                // Prevent the view from propagating the event to the selection model if configured to do so.
                return !me.stopSelection;
            }
        } else {
            return me.callParent(arguments);
        }
    }
});
var isIE8 = true;
isIE8 = getBrowserInfo();

/***************全角字符转换为半角字符方法**************************/
//名称：全角字符转换为半角字符方法
//功能：完成全角向半角字符转换
//创建人：王群
//开发人员：王群
//创建日期：2013-09-26
/***************全角字符转换为半角字符方法***********************/
function ToCDB(str) {
    var tmp = "";
    if (str != null) {
        var reg = new RegExp("['\"%]");
        var reg1 = new RegExp("[\>\<]");
        for (var i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
                tmp += String.fromCharCode(str.charCodeAt(i) - 65248).replace(reg, '').replace(reg1, '');
            }
            else {
                tmp += String.fromCharCode(str.charCodeAt(i)).replace(reg, '').replace(reg1, '');
            }
        }
    }
    return tmp;
}

/***************全局捕获异常**************************/
//名称：全局捕获异常
//功能：全局捕获异常
//创建人：王群
//开发人员：王群
//创建日期：2013-12-20

/***************提示信息的公共方法**************************/
//名称：提示信息的公共方法
//功能：提示信息的公共方法
//创建人：王群
//开发人员：王群
//创建日期：3013-10-16
//type:INFO：提示，ERROR：错误，QUESTION:询问,WARNING：警告
/***************提示信息的公共方法***********************/
function MessageBox(mssage, type, Fn) {
    var reg = new RegExp("[!！.。?？]");
    //带有li样式的验证
    var liReg = new RegExp("</li>");
    if (mssage == null || mssage == undefined) {
        Ext.MessageBox.show({ title: "错误", msg: ajaxRequestFail,
            buttons: Ext.MessageBox.OK,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.ERROR
        });
    }
    else if (type == "WARNING") {
        if (liReg.test(mssage)) {
            mssage = mssage.replace(reg, "").replace("</li>", "！</li>");
        }
        else {
            mssage = mssage.replace(reg, "") + "！";
        }
        Ext.MessageBox.show({ title: "警告", msg: mssage,
            buttons: Ext.MessageBox.OK,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.WARNING
        });
    }
    else if (type == 'ERROR') {
        if (liReg.test(mssage)) {
            mssage = mssage.replace(reg, "").replace("</li>", "！</li>");
        }
        else {
            mssage = mssage.replace(reg, "") + "！";
        }
        Ext.MessageBox.show({ title: "错误", msg: mssage,
            buttons: Ext.MessageBox.OK,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.ERROR
        });
    }
    else if (type == 'QUESTION') {
        if (liReg.test(mssage)) {
            mssage = mssage.replace(reg, "").replace("</li>", "？</li>");
        }
        else {
            mssage = mssage.replace(reg, "") + "？";
        }
        Ext.MessageBox.show({ title: "询问", msg: mssage,
            buttons: Ext.MessageBox.YESNO,
            closable: false,
            defaultFocus: "no",
            fn: Fn,
            icon: Ext.MessageBox.QUESTION
        });
    }
    else {
        if (liReg.test(mssage)) {
            mssage = mssage.replace(reg, "").replace("</li>", "！</li>");
        }
        else {
            mssage = mssage.replace(reg, "") + "！";
        }
        Ext.MessageBox.show({ title: "提示", msg: mssage,
            buttons: Ext.MessageBox.OK,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.INFO
        });
    }
}
////自动关闭提示窗体
function AutoCloseMessageBox(mssage, type, Fn) {
    if (type == "WARNING") {
        Ext.MessageBox.show({ title: "警告", msg: mssage,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.WARNING
        });
    }
    else if (type == 'ERROR') {
        Ext.MessageBox.show({ title: "错误", msg: mssage,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.ERROR
        });
    }
    else {
        Ext.MessageBox.show({ title: "提示", msg: mssage,
            closable: false,
            fn: Fn,
            icon: Ext.MessageBox.INFO
        });
    }
    setTimeout(function () {
        Ext.MessageBox.close();
    }, 1000)
}
/***************屏蔽backspace返回上一页的公共方法**************************/
//名称：屏蔽backspace返回上一页的公共方法
//功能：屏蔽backspace返回上一页的公共方法
//创建人：王群
//开发人员：王群
//创建日期：2013-10-29
/***************屏蔽backspace返回上一页的公共方法***********************/
Ext.EventManager.on(Ext.isIE ? document : window, 'keydown', function (e, t) {
    if (e.getKey() == e.BACKSPACE &&
    e.browserEvent.srcElement.type != 'text' &&
    e.browserEvent.srcElement.type != 'textarea' &&
    e.browserEvent.srcElement.type != 'password' ||
    t.readOnly) {
        e.stopEvent();
    }
})

////处理特殊字符（#，&，@）
function ReplaceText(text) {
    var newText = text;
    newText = text.replace(/\#/g, "#");
    newText = newText.replace(/\&/g, "&");
    newText = newText.replace(/\@/g, "@");
    return newText;
}

//方案三
function CommonTest() {
    var vthis = this;
    //    vthis.id = "53-1";
    //获取属性控件验证配置信息
    Ext.Ajax.request({ async: false, url: '../CodeGenerate/GetAttrConfigString',
        params: { AttrID: vthis.id },
        success: function (respf) {
            if (respf.responseText == "") {
                return;
            }
            var VailtorConfigData = Ext.JSON.decode(respf.responseText);
            vthis.enforceMaxLength = true;
            for (var i = 0; i < VailtorConfigData.length; i++) {
                ////控件通用验证配置
                switch (VailtorConfigData[i].Key) {
                    case "maxLength":
                        vthis.maxLength = VailtorConfigData[i].Value;
                        break;
                    case "minLength":
                        vthis.minLength = VailtorConfigData[i].Value;
                        break;
                    case "regex":
                        vthis.regex = new RegExp(VailtorConfigData[i].Value);
                    default:
                        break;
                }
                //                if (vthis.xtype == 'numberfield' || vthis.xtype == 'datefield') {
                //                    switch (VailtorConfigData[i].Key) {
                //                        case "maxValue":
                //                            vthis.maxValue = VailtorConfigData[i].Value;
                //                            break;
                //                        case "minValue":
                //                            vthis.minValue = VailtorConfigData[i].Value;
                //                            break;
                //                        default:
                //                            break;
                //                    }
                //                }
                if (vthis.xtype == 'numberfield') {
                    numberFieldVailtorConfig(vthis, VailtorConfigData[i]);
                    //                    switch (VailtorConfigData[i].Key) {
                    //                        case "decimalPrecision":
                    //                            vthis.decimalPrecision = VailtorConfigData[i].Value;
                    //                            break;
                    //                        default:
                    //                            break;
                    //                    }
                } ///control
                if (vthis.xtype == 'datefield') {
                    dateFieldVailtorConfig(vthis, VailtorConfigData[i]);
                    //                    switch (VailtorConfigData[i].Key) {
                    //                        case "format":
                    //                            vthis.format = VailtorConfigData[i].Value;
                    //                            break;
                    //                        default:
                    //                            break;
                    //                    }
                }
            }
            //            if (VailtorConfigData != null && VailtorConfigData != undefined) {
            //                if (vthis.xtype == 'textfield') {//文本类型
            //                    vthis.maxLength = VailtorConfigData.maxLength;                     //允许输入的最大长度
            //                    vthis.minLength = VailtorConfigData.minLength;                      //允许输入的最小长度
            //                    vthis.regex = new RegExp(VailtorConfigData.regex);                 //允许输入的正则表达式
            //                }
            //                else if (vthis.xtype == 'numberfield') {
            //                    vthis.maxLength = VailtorConfigData.maxLength;                     //允许输入的最大长度
            //                    vthis.minLength = VailtorConfigData.minLength;                      //允许输入的最小长度
            //                    vthis.maxValue = VailtorConfigData.maxValue;                         //允许输入的最大值
            //                    vthis.minVaue = VailtorConfigData.minVaue;                            //允许输入的最小值
            //                    vthis.decimalPrecision = VailtorConfigData.decimalPrecision;    //允许小数点后保留的位数
            //                    vthis.regex = new RegExp(VailtorConfigData.regex);                 //允许输入的正则表达式

            //                }
            //                else if (vthis.xtype == 'datefield') {
            //                    vthis.maxLength = VailtorConfigData.maxLength;                     //允许输入的最大长度
            //                    vthis.minLength = VailtorConfigData.minLength;                      //允许输入的最小长度
            //                    vthis.maxValue = VailtorConfigData.maxValue;                         //允许输入的最大值
            //                    vthis.minVaue = VailtorConfigData.minVaue;                            //允许输入的最小值
            //                    vthis.regex = new RegExp(VailtorConfigData.regex);                 //允许输入的正则表达式
            //                }
            //            }
        },
        failure: function (respf) {
            var data = Ext.JSON.decode(respf.responseText);
            if (data != undefined) {
                MessageBox(data.message, "ERROR");
            }
            else {
                MessageBox(ajaxRequestFail, "ERROR");
            }
            return;
        }
    });
}
////设置UI界面控件是否显示
function SetUIResourceItemsVisible(uiId) {
    Ext.Ajax.request({
        url: '/UIResource/GetItemsOfTeamRoleUIRes',
        params: {
            uiResId: uiId
        },
        success: function (response) {
            var resultText = response.responseText;
            if (resultText != "") {
                var result = Ext.JSON.decode(response.responseText);
                if (result.length > 0) {
                    for (var i = 0; i < result.length; i++) {
                        Ext.getCmp(result[i].DefaultControlName).setVisible(true);
                        Ext.getCmp(result[i].DefaultControlName + "Line").setVisible(true);
                    }
                }
            }
        }
    });
}
////数字控件验证配置
function numberFieldVailtorConfig(vthis, VailtorConfigData) {
    switch (VailtorConfigData.Key) {
        case "maxValue":
            vthis.maxValue = VailtorConfigData.Value;
            break;
        case "minValue":
            vthis.minValue = VailtorConfigData.Value;
            break;
        case "decimalPrecision":
            vthis.decimalPrecision = VailtorConfigData.Value;
            break;
        default:
            break;
    }
}
////日期控件验证配置
function dateFieldVailtorConfig(vthis, VailtorConfigData) {
    switch (VailtorConfigData.Key) {
        case "maxValue":
            vthis.maxValue = VailtorConfigData.Value;
            break;
        case "minValue":
            vthis.minValue = VailtorConfigData.Value;
            break;
        case "format":
            vthis.format = VailtorConfigData.Value;
            break;
        default:
            break;
    }
}
//进行千分分隔符的格式化
function Test() {
    var ss = Ext.util.Format.number(String(122), "0,000,000.00");
}
////添加最近访问的项目
function InsertRecentAccessItem(masterId) {

    Ext.Ajax.request({ async: false, loadMask: true,
        url: '../Misc/InsertRecentAccessItem',
        params: { masterId: masterId },
        success: function (respf) {
            var data = Ext.JSON.decode(respf.responseText, true);
            if (data == null) {
                MessageBox('数据操作失败!', 'ERROR');
                return;
            }
            else {
                if (!data.success) {
                    MessageBox('数据操作失败!', 'ERROR');
                }
            }
        }
    });
}
////将16进制的颜色代码转成10进制的数字 RGB(red, blue, green)
function reverseColor(rgbColor) {
    rgbColor = rgbColor.replace(/\s/g, "");
    var arrRGB = new Array(3);
    if (rgbColor.indexOf("rgb") > -1) {
        var colorReg = /\s*\d+,\s*\d+,\s*\d+/i;
        var t = colorReg.exec(rgbColor)[0].split(",");
        for (var i = 0; i < arrRGB.length; i++) {
            arrRGB[i] = 255 - t[i];
        }
    }
    else if (rgbColor.indexOf("#") > -1) {
        if (rgbColor.length > 4) {
            var j = 1;
            for (var i = 0; i < arrRGB.length; i++) {
                arrRGB[i] = 255 - parseInt(rgbColor.substr((i + j), 2), 16);
                j += 1;
            }
        }
        else {
            for (var i = 0; i < arrRGB.length; i++) {
                var t = rgbColor.substr((i + 1), 1);
                t = t + t;
                arrRGB[i] = 255 - parseInt(t, 16);
            }
        }
    }
    return "rgb(" + arrRGB.join(",") + ")";
}
//重写Ext.selection.Model,防止错误"由于该控件目前不可见、未启用或其类型不允许，因此无法将焦点移向它。"
Ext.override(Ext.selection.Model, {
    select: function (records, keepExisting, suppressEvent) {
        // Automatically selecting eg store.first() or store.last() will pass undefined, so that must just return;
        if (Ext.isDefined(records)) {
            this.doSelect(records, keepExisting, suppressEvent);
        }
    },

    /**
    * Deselects a record instance by record instance or index.
    * @param {Ext.data.Model[]/Number} records An array of records or an index
    * @param {Boolean} [suppressEvent=false] True to not fire a deselect event
    */
    deselect: function (records, suppressEvent) {
        this.doDeselect(records, suppressEvent);
    },

    doSelect: function (records, keepExisting, suppressEvent) {
        var me = this,
            record;

        if (me.locked || !me.store) {
            return;
        }
        if (typeof records == "number") {
            record = me.store.getAt(records);
            // No matching record, jump out
            if (!record) {
                return;
            }
            records = [record];
        }
        if (me.selectionMode == "SINGLE" && records) {
            record = records.length ? records[0] : records;
            me.doSingleSelect(record, suppressEvent);
        } else {
            me.doMultiSelect(records, keepExisting, suppressEvent);
        }
    },

    doMultiSelect: function (records, keepExisting, suppressEvent) {
        var me = this,
            selected = me.selected,
            change = false,
            i = 0,
            len, record;

        if (me.locked) {
            return;
        }


        records = !Ext.isArray(records) ? [records] : records;
        len = records.length;
        if (!keepExisting && selected.getCount() > 0) {
            if (me.doDeselect(me.getSelection(), suppressEvent) == false) {
                return;
            }
            // TODO - coalesce the selectionchange event in deselect w/the one below...
        }

        function commit() {
            selected.add(record);
            change = true;
        }

        for (; i < len; i++) {
            record = records[i];
            if (keepExisting && me.isSelected(record)) {
                continue;
            }
            me.lastSelected = record;

            me.onSelectChange(record, true, suppressEvent, commit);
        }
        if (!me.preventFocus) {
            //me.setLastFocused(record, suppressEvent);//shaocx 11/1 注释
        }
        // fire selchange if there was a change and there is no suppressEvent flag
        me.maybeFireSelectionChange(change && !suppressEvent);
    },
    doSingleSelect: function (record, suppressEvent) {
        var me = this,
            changed = false,
            selected = me.selected;

        if (me.locked) {
            return;
        }
        // already selected.
        // should we also check beforeselect?
        if (me.isSelected(record)) {
            return;
        }

        function commit() {
            me.bulkChange = true;
            if (selected.getCount() > 0 && me.doDeselect(me.lastSelected, suppressEvent) == false) {
                delete me.bulkChange;
                return false;
            }
            delete me.bulkChange;

            selected.add(record);
            me.lastSelected = record;
            changed = true;
        }

        me.onSelectChange(record, true, suppressEvent, commit);

        if (changed) {
            if (!suppressEvent && !me.preventFocus) {
                //me.setLastFocused(record);//shaocx 11/1 注释
            }
            me.maybeFireSelectionChange(!suppressEvent);
        }
    }
}
);

function getBrowserInfo() {
    var agent = navigator.userAgent.toLowerCase();
    var reg_ie = /msie[\d.]+/gi;
    var reg_ff = /firefox\/[\d.]+/gi;
    var reg_chrome = /chrome\/[\d.]+/gi;
    var reg_saf = /safari\/[\d.]+/gi;
    var isIE = agent.indexOf("msie") > 0;
    if (isIE) {
        var v = isIE ? /\d+/.exec(agent.split(";")[1]) : 'no ie';
        if (v <= 8) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        return false;
    }
}

function isLessIE8() {
    var ua = navigator.userAgent;
    var isIE = ua.indexOf("MSIE") > -1;
    var v = isIE ? /\d+/.exec(ua.split(";")[1]) : 'no ie';
    var re = v < 8;
    
    return re;
}
document.oncontextmenu = function (e) {
    return false;
}
////使浏览器后退按钮失效
window.history.forward(1);

var appinfo = '';
var loginId = '';
var funcClassifiedSystem=function GetISSECURITYProperty() {
    var result = false;
    Ext.Ajax.request({
        async: false, //
        url: '/Validation/GetClassifiedSystem',
        success: function (responf) {
            var data = Ext.JSON.decode(responf.responseText, true);
            if (!data.success) {
                result = false;
            } else {
                var dataItem = Ext.JSON.decode(data.message, true);
                result = dataItem;
            }
        },
        failure: function () {
            result = false;
        }
    });
    return result;
}

